﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Project5188.BUS
{
    public class Users : DetailView<user>
    {
        private project5188Entities _context;
        // ReSharper disable InconsistentNaming
        private new List<user> EntityList;
        private new user Entity;
        // ReSharper restore InconsistentNaming

        public long TransactionId { get; private set; }

        #region Overrides of DetailView<user>

        public override List<user> GetEntityList()
        {
            _context = new project5188Entities();
            EntityList = _context.users.Where(a => !a.IsDeleted).OrderBy(a => a.ID).ToList();

            return EntityList;
        }

        public override List<user> GetEntityById(long id)
        {
            _context = new project5188Entities();
            EntityList = _context.users.Where(a => a.ID == id && !a.IsDeleted).OrderBy(a => a.ID).ToList();

            return EntityList;
        }

        public override user GetEntity()
        {
            _context = new project5188Entities();
            Entity = new user();
            return Entity;
        }

        public override void Update()
        {
            _context.SaveChanges();
        }

        public override void Insert()
        {
            if (ExistUser(Entity.Username))
            {
                throw new Exception("Seçtiğiniz kullanıcı sistemde mevcuttur. Lütfen başka bir kullanıcı adı seçiniz.");
            }

            _context.AddTousers(Entity);
            _context.SaveChanges();

            TransactionId = Entity.ID;
        }

        #endregion

        public List<user> GetEntityListByParameters(string userName)
        {
            _context = new project5188Entities();

            EntityList = _context.users.Where(a => (a.Username.Contains(userName)) && !a.IsDeleted).OrderBy(a => a.ID).ToList();

            return EntityList;
        }

        public List<user> LoginUser(string username, string password)
        {
            _context = new project5188Entities();

            var hashedPassword = Extensions.Md5Hashing(password);

            return
                _context.users.Where(a => a.Username.Contains(username) && a.Pass == hashedPassword).
                    ToList();
        }

        public bool ExistUser(string userName)
        {
            _context = new project5188Entities();

            return _context.users.Where(a => a.Username == userName && !a.IsDeleted).Count() > 0;
        }

        public List<user> GetUserListExceptCurrentUserId(long userId)
        {
            _context = new project5188Entities();
            EntityList = _context.users.Where(a => a.ID != userId && !a.IsDeleted).OrderBy(a => a.ID).ToList();

            return EntityList;
        }
    }
}
